# 生成html---解析html---下载图片（wximg_disk）
# 打开微信公众平台---根据当前时间创建分组---手动上传图片---获取图片url（disk_url）
# 用url替换html中的wximg---获得新的html
import os

from html_parse import HtmlParse
from wx_upload import WxUpload


def html_parse(content):
    parse = HtmlParse(content)
    dict = parse.get_dict()
    return dict


def get_upload_input():
    pass


def upload_input():
    result = input('是否上传完成？输入：y/n（y完成，n未完成）')
    result = result.lower()
    while result != 'y':
        result = input('是否上传完成？输入：y/n（y完成，n未完成）')
        result = result.lower()
        if result == 'y':
            break

    return result


def gene_new_html_path(path):
    dir = os.path.dirname(path)
    old_name = os.path.basename(path)
    names = old_name.split('.')
    new_name = names[0] + "_新."
    return os.path.join(dir, new_name + names[1])


if __name__ == '__main__':
    path = input('请输入文件路径：')
    # path = 'test1.html'
    new_path = gene_new_html_path(path)
    try:
        with open(path, 'r', encoding='utf-8') as f1:
            html_content = f1.read()
    except:
        print('未找到文件：' + path)
        exit(-1)

    wximg_disk = html_parse(html_content)
    wximg_count = len(wximg_disk.keys())
    print('需替换 %d 个图片' % wximg_count)

    url_dict = None
    upload = WxUpload()
    if upload.get_status() == 11:
        upload_result = upload_input()
        if upload_result == 'y':
            url_dict = upload.get_upload_url()

    if url_dict:
        print('正在替换图片')
        index = 0
        for wximg in wximg_disk:
            path = wximg_disk[wximg]
            name = os.path.basename(path)
            url = url_dict.get(name, '')
            if url:
                html_content = html_content.replace(wximg, url)
                index += 1
            else:
                print('未找到上传的图片%d : %s' % (index, name))

        print('共替换 %d 个图片' % index)

        if wximg_count != index:
            print('需替换 %d 个图片，共替换 %d 个图片' % (wximg_count, index))
            print('%d个图片有误' % (wximg_count - index))
        else:
            print('所有图片替换完成')

        with open(new_path, 'w', encoding='utf-8') as f2:
            f2.write(html_content)
            print('------>代码保存成功')
            print(new_path)
